
package com.base.lib.net.listener;


import com.base.lib.mvp.view.IBaseView;
import com.base.lib.util.LogUtils;

import java.lang.ref.WeakReference;

/**
 * Author: neo.duan
 * Date: 2017/02/20 17:06
 * Desc: 网络请求回调：使用静态内部类，防止持有外部类引用
 */
public class BaseHttpResponseListener implements IHttpListener {
    protected final String TAG = getClass().getSimpleName();

    private WeakReference<IBaseView> reference;
    private boolean isShowLoading;

    public BaseHttpResponseListener(IBaseView baseView) {
        reference = new WeakReference<>(baseView);
    }

    @Override
    public void onResponse(int code, Object jsonObject, String status) {
        switch (code) {
            //请求开始
            case RESPONSE_START:
                onStart();
                break;
            //请求成功且服务器成返回
            case RESPONSE_SUCCESS:
                onSuccess(jsonObject);
                break;
            //请求失败：服务器返回错误或者超时，弹出提示
            case RESPONSE_FAIL:
                if (jsonObject == null) {
                    onFail(status, "服务器开了点小差，请稍后再试");
                } else {
                    onFail(status, jsonObject.toString());
                }
                break;
            //请求已取消
            case RESPONSE_CANCEL:
                onCancel(jsonObject == null ? "" : jsonObject.toString());
                break;
            //网络错误：无网络
            case RESPONSE_ERROR:
                onError();
                break;
            //网络错误：无网络
            case RESPONSE_DONE:
                onDone();
                break;
            default:
                break;
        }
    }

    public void onStart() {
        IBaseView baseView = reference.get();
        if (baseView != null) {
            baseView.showLoading();
            isShowLoading = true;
        }
    }

    public void onSuccess(Object obj) {

    }

    public void onFail(String status, String msg) {
        LogUtils.e(TAG, msg);
        IBaseView baseView = reference.get();
        if (baseView != null) {
            baseView.showMessage(msg);
        }
    }

    public void onCancel(String msg) {
        LogUtils.e(TAG, msg);
    }

    public void onDone() {
        IBaseView baseView = reference.get();
        if (baseView != null && isShowLoading) {
            baseView.hideLoading();
        }
    }

    public void onError() {
        IBaseView baseView = reference.get();
        if (baseView != null) {
            baseView.showNetError();
            baseView.showMessage("网络连接不畅，请检查一下您的网络！");
        }
    }
}
